
package com.tianyang.yukuaifu.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Description 日期操作工具类.
 */

public class DateUtils {

    public static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;

    /**
     * 日期
     */
    public static final String TODAY = "今天";
    public static final String YESTERDAY = "昨天";
    public static final String TOMORROW = "明天";
    public static final String BEFORE_YESTERDAY = "前天";
    public static final String AFTER_TOMORROW = "后天";
    public static final String SUNDAY = "星期日";
    public static final String MONDAY = "星期一";
    public static final String TUESDAY = "星期二";
    public static final String WEDNESDAY = "星期三";
    public static final String THURSDAY = "星期四";
    public static final String FRIDAY = "星期五";
    public static final String SATURDAY = "星期六";


    /**
     * 时间格式：yyyy-MM-dd HH:mm
     */
    public static final String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss";

    public static String formatDateTime(long time, String formatString) {
        time = time * 1000;
        long curTime = System.currentTimeMillis();
        long offset = TimeZone.getDefault().getRawOffset();
        int day = (int) ((curTime + offset) / android.text.format.DateUtils.DAY_IN_MILLIS - (time + offset)
                / android.text.format.DateUtils.DAY_IN_MILLIS);
        String timeString;
        switch (day) {
            case 0:
                timeString = "今天";
                break;
            case 1:
                timeString = "昨天";
                break;
            case 2:
                timeString = "前天";
                break;
            default:
                timeString = new SimpleDateFormat(formatString).format(new Date(time));
                break;
        }

        return timeString;
    }

    public static String formatDateTime(Date date, String formatString) {
        return new SimpleDateFormat(formatString).format(date);
    }

    public static String formatTime(String target, String targetFormat, String formatString) {
        SimpleDateFormat sdf = new SimpleDateFormat(targetFormat);
        String dateString = "";
        try {
            Date date = sdf.parse(target);
            SimpleDateFormat targetSdf = new SimpleDateFormat(formatString);
            dateString = targetSdf.format(date);
        } catch (Exception e) {
        }
        return TextUtils.isEmpty(dateString) ? target : dateString;
    }

    public static Date string2Date(String target, String format) {
        DateFormat df = new SimpleDateFormat(format);
        try {
            return df.parse(target);
        } catch (Exception e) {
        }
        return new Date();
    }

    public static int[] timeDiff(long sTime, long cTime) {
        // 按照传入的格式生成一个simpledateformate对象
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        try {
            // 获得两个时间的毫秒时间差异
            diff = sTime - cTime;
            long day = diff / nd;// 计算差多少天
            long hour = diff % nd / nh;// 计算差多少小时
            long min = diff % nd % nh / nm;// 计算差多少分钟
//            long sec = diff % nd % nh % nm / ns;// 计算差多少秒
            return new int[]{(int) Math.abs(day), (int) Math.abs(hour), (int) Math.abs(min)};
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String[] formatTranTime(String time) {
        Date date = DateUtils.string2Date(time, DateUtils.FORMAT_TIME);
        return formatTranTime(date.getTime());
    }

    public static String[] formatTranTime(long time) {
        long curTime = System.currentTimeMillis();
        long offset = TimeZone.getDefault().getRawOffset();
        int day = (int) ((curTime + offset) / android.text.format.DateUtils.DAY_IN_MILLIS - (time + offset)
                / android.text.format.DateUtils.DAY_IN_MILLIS);
        String timeString = "";
        String format = "HH:mm";
        switch (day) {
            case 0:
                timeString += "今天";
                break;
            case 1:
                timeString += "昨天";
                break;
            case 2:
                timeString += "前天";
                break;
            default:
                SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
                timeString = sdf.format(new Date(time));
                format = "MM-dd";
                break;
        }
        return new String[]{timeString, new SimpleDateFormat(format).format(new Date(time))};
    }

    public static long getTime(String timeStr, String format) {
        long time = 0l;
        DateFormat df = new SimpleDateFormat(format);
        try {
            time = df.parse(timeStr).getTime() / 1000;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    public static String getTime(long time, String format) {
        DateFormat df = new SimpleDateFormat(format);
        return df.format(new Date(time));
    }

    public static long getTime(String timeStr) {
        long time = 0l;
        if (timeStr.indexOf("-") > 0) {
            DateFormat df = new SimpleDateFormat(FORMAT_TIME);
            try {
                time = df.parse(timeStr).getTime() / 1000;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            time = Long.parseLong(timeStr);
        }
        return time;
    }

    /**
     * 将毫秒数格式化成时间
     *
     * @param time 需要格式的毫秒
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatTime(long time) {
        return new SimpleDateFormat(FORMAT_TIME).format(new Date(time));
    }

    @SuppressLint("SimpleDateFormat")
    public static String formatTime(long time, String format) {
        return new SimpleDateFormat(format).format(new Date(time));
    }

    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(String data, String formatType) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = formatter.parse(data);
            return new SimpleDateFormat(formatType).format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String timeToString(int hour, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        return new SimpleDateFormat("HH:mm").format(calendar.getTimeInMillis());
    }

    /**
     * 将日期信息转换成今天、明天、后天、星期
     *
     * @param date
     * @return
     */
    public static String laterTime(Date date) {
        Calendar today = Calendar.getInstance();
        Calendar target = Calendar.getInstance();

        try {
            today.setTime(new Date());
            today.set(Calendar.HOUR, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
            target.setTime(date);
            target.set(Calendar.HOUR, 0);
            target.set(Calendar.MINUTE, 0);
            target.set(Calendar.SECOND, 0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis();
        int xcts = (int) (intervalMilli / (24 * 60 * 60 * 1000));
        if (xcts < -2) {
            return "活动已经";
        }
        switch (xcts) {
            case 0:
                return TODAY;
            case 1:
                return TOMORROW;
            case 2:
                return AFTER_TOMORROW;
            case -1:
                return YESTERDAY;
            case -2:
                return BEFORE_YESTERDAY;
            default:
                return xcts + "天后";
        }

    }

    /**
     * 转换日期 转换为更为人性化的时间
     *
     * @param time 时间
     * @return
     */
    public static String translateDate(long time, long curTime) {
        long oneDay = 24 * 60 * 60;
        Calendar today = Calendar.getInstance();    //今天
        today.setTimeInMillis(curTime * 1000);
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        long todayStartTime = today.getTimeInMillis() / 1000;
        if (time >= todayStartTime) {
            long d = curTime - time;
            if (d <= 60) {
                return "刚刚";
            } else if (d <= 60 * 60) {
                long m = d / 60;
                if (m <= 0) {
                    m = 1;
                }
                return m + "分钟前";
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("今天 HH:mm");
                Date date = new Date(time * 1000);
                String dateStr = dateFormat.format(date);
                if (!TextUtils.isEmpty(dateStr) && dateStr.contains(" 0")) {
                    dateStr = dateStr.replace(" 0", " ");
                }
                return dateStr;
            }
        } else {
            if (time < todayStartTime && time > todayStartTime - oneDay) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("昨天 HH:mm");
                Date date = new Date(time * 1000);
                String dateStr = dateFormat.format(date);
                if (!TextUtils.isEmpty(dateStr) && dateStr.contains(" 0")) {

                    dateStr = dateStr.replace(" 0", " ");
                }
                return dateStr;
            } else if (time < todayStartTime - oneDay && time > todayStartTime - 2 * oneDay) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("前天 HH:mm");
                Date date = new Date(time * 1000);
                String dateStr = dateFormat.format(date);
                if (!TextUtils.isEmpty(dateStr) && dateStr.contains(" 0")) {
                    dateStr = dateStr.replace(" 0", " ");
                }
                return dateStr;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = new Date(time * 1000);
                String dateStr = dateFormat.format(date);
                if (!TextUtils.isEmpty(dateStr) && dateStr.contains(" 0")) {
                    dateStr = dateStr.replace(" 0", " ");
                }
                return dateStr;
            }
        }
    }

    public static long getWeekDifference(long date1, long date2) {
        long min = Math.min(date1, date2);
        long max = Math.max(date1, date2);
        long week = (max - min) / android.text.format.DateUtils.WEEK_IN_MILLIS;
        long time = min + week * android.text.format.DateUtils.WEEK_IN_MILLIS;
        if (!isSameWeek(time, max)) {
            week++;
        }
        return week;
    }

    public static boolean isSameWeek(long date1, long date2) {

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        calendar2.setTimeInMillis(date2);
        if (calendar1.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar1.add(Calendar.DATE, -1);
        }
        if (calendar2.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar2.add(Calendar.DATE, -1);
        }
        int subYear = calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
        if (calendar1.get(Calendar.WEEK_OF_YEAR) == calendar2.get(Calendar.WEEK_OF_YEAR)) {
            if (subYear == 0) {
                return true;
            } else if (subYear == 1 && calendar2.get(Calendar.MONTH) == 11) {
                return true;
            } else if (subYear == -1 && calendar1.get(Calendar.MONTH) == 11) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否同一天
     *
     * @param lastTime
     * @return true 同一天
     */
    public static boolean isSame24HourDay(long lastTime) {
        Date start = new Date(TimeManager.getInstance().getCurTimeMillis());
        Date end = new Date(lastTime);
        long cha = start.getTime() - end.getTime();
        if (cha < 0) {
            return false;
        }
        double result = cha * 1.0 / (1000 * 60 * 60);
        if (result <= 24) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param time 单位毫秒
     * @return
     */
    public static boolean isSameDay(long time) {
        if (time == 0)
            return true;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(TimeManager.getInstance().getCurTimeMillis());

        int day = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTimeInMillis(time);
        int wishDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (day != wishDay) {// 不是同一天
            return false;
        }
        return true;// 等于同一天
    }

    public static boolean isSupportPaymentTime(String timeLimit) {
//        Date now = Calendar.getInstance().getTime();
        Date now = new Date(TimeManager.getInstance().getCurTimeMillis());
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        String start = timeLimit.split(",")[0];
        String end = timeLimit.split(",")[1];

        // 开始时间
        startDate.set(Calendar.HOUR_OF_DAY, Integer.parseInt(start.split(":")[0]));
        startDate.set(Calendar.MINUTE, Integer.parseInt(start.split(":")[1]));
        startDate.set(Calendar.SECOND, 0);

        // 结束时间
        endDate.set(Calendar.HOUR_OF_DAY, Integer.parseInt(end.split(":")[0]));
        endDate.set(Calendar.MINUTE, Integer.parseInt(end.split(":")[1]));
        endDate.set(Calendar.SECOND, 59);
        // 判断跨天,如果开始小时，大于结束小时肯定跨天时间
        if (Integer.parseInt(start.split(":")[0]) > Integer.parseInt(end.split(":")[0])) {
            Calendar ktendDate = Calendar.getInstance();
            Calendar ktstartDate = Calendar.getInstance();

            ktstartDate.set(Calendar.HOUR_OF_DAY, 0);
            ktstartDate.set(Calendar.MINUTE, 0);
            ktstartDate.set(Calendar.SECOND, 0);

            ktendDate.set(Calendar.HOUR_OF_DAY, 23);
            ktendDate.set(Calendar.MINUTE, 59);
            ktendDate.set(Calendar.SECOND, 59);

            if (startDate.getTimeInMillis() <= now.getTime() && now.getTime() <= ktendDate.getTimeInMillis()) {
                return true;
            }

            if (ktstartDate.getTimeInMillis() <= now.getTime() && now.getTime() <= endDate.getTimeInMillis()) {
                return true;
            }
            return false;
        } else {
            // 规定时间内返回true
            if (startDate.getTimeInMillis() <= now.getTime() && now.getTime() <= endDate.getTimeInMillis()) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 从时间(毫秒)中提取出时间(时:分)
     * @param millisecond
     * @return
     */
    public static String getTimeFromMillisecond(long millisecond) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Long hour = millisecond/ hh;
        Long minute = (millisecond - hour * hh) / mi;
//        Long second = (millisecond - hour * hh - minute * mi) / ss;
        return hour + "小时" + minute + "分钟";
    }

    /**
     * 获取当前时间
     */
    @SuppressLint("SimpleDateFormat")
    public static String getCurrentTime(String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return  simpleDateFormat.format(date);
    }

    /**
     * 获取30天以前的日期
     */
    @SuppressLint("SimpleDateFormat")
    public static String getTimeAgo(int days, String format) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -days);
        return new SimpleDateFormat(format).format(now.getTime());
    }

    /**
     * 获取当前年月
     */
    @SuppressLint("SimpleDateFormat")
    public static String getCurrentMonth() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    /**
     * 获取时间差(天数)
     */
    @SuppressLint("SimpleDateFormat")
    public static int getDifferenceTime(String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int days = 0;
        try {
            Date date1 = sdf.parse(startDate);
            Date date2 = sdf.parse(endDate);
            days = TimeUtils.differentDays(date1, date2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }
}
